<?php

declare (strict_types=1);

namespace App\Http\Controllers\Api;

use App\Extends\Libs\BaseController;
use App\Models\Xs\XsUser;
use Illuminate\Http\Request;

class Api extends BaseController
{
    protected string $module = 'api';


    /**
     * @var string
     */
    private string $key = 'crift1vcd6bdPMDm';

    private string $vi = '3iKMn0AHaIhq5d7M';

    public function __initialize(): void
    {
        parent::__initialize();

    }

    private array $partners = [
        'xs'
    ];

    public function push(Request $request)
    {
        $appId = $request->header('appid');
        $t = $request->header('t');
        $sign = $request->header('sign');
        $key = $this->key;
        // 验证appID
        if (empty($appId)) {
            return $this->error('appid error', 10001);
        }
        // 验证合作伙伴
        if (!in_array($appId, $this->partners)) {
            return $this->error('illegal partner', 10002);
        }
        // 验证timestamp
        if (empty($t)) {
            return $this->error('timestamp ERROR', 10003);
        }
        // 验证timestamp实效性,测试账号不验证
        if (time() - $t > 60) {
            return $this->error('sign expired', 10004);
        }

        $oSign = md5(sha1($appId . $t) . $key); //v1.0 简单版本兼容

        if ($oSign !== $sign) {
            return $this->error('sign error', 10005);
        }

        $data = $request->post('data');

        if (empty($data)) {
            return $this->error('data 不为空', 10006);
        }

        $aes = new Aes($this->key, $this->vi);


        $data = json_decode($aes->decrypt($data), true);


        if (empty($data)) {
            return $this->error('数据解密失败', 10007);
        }


        $mobile = $data['mobile'] ?? null;
        $token = $data['token'] ?? null;

        if (empty($mobile)) {
            return $this->error('手机号必填', 10008);
        }

        if (empty($token)) {
            return $this->error('token必填', 10009);
        }

        if (!preg_match('/^1[3456789]\d{9}$/', $mobile)) {
            return $this->error('请输入正确的手机号', 100010);
        }

        $ua = $data['ua'] ?? null;
        $name = $data['name'] ?? null;
        $model = XsUser::query()->where('mobile', $mobile)->first();
        if (!$model) {
            $model = new XsUser();
        }
        $model->token = $token;
        $model->mobile = $mobile;
        if ($ua) {
            $model->ua = $ua;
        }
        if ($name) {
            $model->name = $name;
        }

        $model->save();
        return $this->success();
    }

    /**
     * 创建加密参数
     */
    private function encrypt()
    {
        $json = '{
            "ua":" Mozil53WEB/8379",
            "token":" Bearer mFH7aXad5u",
            "mobile":"1377777777",
            "name":"张三 "
        }';


        $aes = new Aes($this->key, $this->vi);
        $data = $aes->encrypt($json);

        return json_encode([
            'data' => $data,
        ]);
    }
}
